package com.k12.admim.controller.operator;

import cn.dev33.satoken.stp.StpUtil;
import com.google.protobuf.ServiceException;
import com.k12.admim.model.dto.RegUserDTO;
import com.k12.admim.model.entity.sys.SysUser;
import com.k12.admim.model.entity.sys.SysUserRole;
import com.k12.admim.model.vo.sys.RegUserVo;
import com.k12.admim.model.vo.sys.SysDeptVo;
import com.k12.admim.service.OperatorRoleService;
import com.k12.admim.service.OperatorUserService;
import com.k12.admim.utils.RequestContextUtil;
import com.k12.admim.model.vo.sys.SysUserVo;
import com.k12.common.model.resp.R;
import com.k12.common.util.PageUtil;
import com.k12.common.util.sign.RsaUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class OperatorUserController {

    @Resource
    private OperatorUserService operatorUserService;


    @Resource
    private OperatorRoleService operatorRoleService;

    @PostMapping("system/user/deptTree")
    public R deptTree() throws ServiceException {
        String tenantId = RequestContextUtil.getTenantId();
        if(StringUtils.isBlank(tenantId)){
            return R.failed("非法登录");
        }
        Long userId = (Long) StpUtil.getLoginId();
        SysUserVo sysUserVo = new SysUserVo();
        sysUserVo.setUserId(userId);
        sysUserVo.setTenantId(Long.parseLong(tenantId));
        List<SysDeptVo> sysDepts = operatorUserService.selectDeptTree(sysUserVo);
        // 构建树状结构
        List<SysDeptVo> tree = buildDeptTree(sysDepts);
        return R.success(tree);
    }



    private List<SysDeptVo> buildDeptTree(List<SysDeptVo> sysDepts) {
        // 创建映射，便于快速查找
        Map<Long, SysDeptVo> nodeMap = new HashMap<>();
        List<SysDeptVo> rootNodes = new ArrayList<>();

        // 初始化所有节点
        for (SysDeptVo dept : sysDepts) {
            SysDeptVo vo = new SysDeptVo();
            vo.setDeptId(dept.getDeptId());
            vo.setDeptName(dept.getDeptName());
            nodeMap.put(dept.getDeptId(), vo);
        }

        // 构建父子关系
        for (SysDeptVo dept : sysDepts) {
            SysDeptVo currentNode = nodeMap.get(dept.getDeptId());
            // 如果是根节点（parentId为0或null）
            if (dept.getParentId() == null || dept.getParentId() == 0) {
                rootNodes.add(currentNode);
            } else {
                // 添加到父节点的子节点列表中
                SysDeptVo parentNode = nodeMap.get(dept.getParentId());
                if (parentNode != null) {
                    parentNode.getChildren().add(currentNode);
                }
            }
        }
        return rootNodes;
    }

    /**
     * 注册
     * 后台管理以分配账号为主
     * 需要判断当前登录人的角色，进行用户类型的选择
     */
    @PostMapping("system/user")
    public R register(@RequestBody RegUserVo regUserVo) {
        //密码加密处理.
        String tenantId = RequestContextUtil.getTenantId();
        if(StringUtils.isBlank(tenantId)){
            return R.failed("非法登录");
        }
        String password = null;
        try {
            password = RsaUtils.decryptByPrivateKey(regUserVo.getPassword());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        regUserVo.setPassword(password);
        regUserVo.setTenantId(tenantId);
        return operatorUserService.register(regUserVo);
    }

    //用户修改
    @PutMapping("system/user")
    public R updateUser(@RequestBody RegUserVo regUserVo) throws ServiceException {
        //密码加密处理.
        String tenantId = RequestContextUtil.getTenantId();
        if(StringUtils.isBlank(tenantId)){
            return R.failed("非法登录");
        }
        String password = null;
        try {
            password = RsaUtils.decryptByPrivateKey(regUserVo.getPassword());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        regUserVo.setPassword(password);
        regUserVo.setTenantId(tenantId);
        return operatorUserService.updateUser(regUserVo);
    }


    //回显
    @GetMapping("system/user/{userId}")
    public R getUser(@PathVariable(value = "userId", required = false) Long userId) {
        String tenantId = RequestContextUtil.getTenantId();
        if(StringUtils.isBlank(tenantId)){
            return R.failed("非法登录");
        }
        List<SysUser> sysDepts = operatorUserService.checkUser(tenantId, userId);
        if (sysDepts == null || sysDepts.isEmpty())
        {
            return R.failed("修改失败，没有访问数据权限");
        }
        RegUserDTO regUserDTO = operatorUserService.getUser(userId,tenantId);
        return R.success(regUserDTO);
    }



    @DeleteMapping("system/user/{userIds}")
    public R delete(@PathVariable Long[] userIds){
        String tenantId = RequestContextUtil.getTenantId();
        if(StringUtils.isBlank(tenantId)){
            return R.failed("非法登录");
        }
        Long loginId = (Long) StpUtil.getLoginId();
        if (ArrayUtils.contains(userIds, loginId))
        {
            return R.failed("当前用户不能删除");
        }
        operatorUserService.deleteByIds(userIds,tenantId);
        return R.success("删除完成");
    }

    /**
     * 重置密码
     */
    @PutMapping("resetPwd")
    public R resetPwd(@RequestBody RegUserVo regUserVo){
        String tenantId = RequestContextUtil.getTenantId();
        if(StringUtils.isBlank(tenantId)){
            return R.failed("非法登录");
        }
        List<SysUser> sysDepts = operatorUserService.checkUser(tenantId, regUserVo.getUserId());
        if (sysDepts == null || sysDepts.isEmpty())
        {
            return R.failed("修改失败，没有访问数据权限");
        }
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        regUserVo.setPassword(passwordEncoder.encode(regUserVo.getPassword()));
        regUserVo.setUpdateBy(String.valueOf(StpUtil.getLoginId()));
        regUserVo.setTenantId(String.valueOf(Long.valueOf(tenantId)));
        operatorUserService.resetPwd(regUserVo);
        return R.success();
    }


    /**
     * 根据用户编号获取授权角色
     */
    @PutMapping("authRole/{userId}")
    public R authRole(Long userId, Long[] roleIds) {
        String tenantId = RequestContextUtil.getTenantId();
        if(StringUtils.isBlank(tenantId)){
            return R.failed("非法登录");
        }
        List<SysUser> sysDepts = operatorUserService.checkUser(tenantId, userId);
        if (sysDepts == null || sysDepts.isEmpty())
        {
            return R.failed("修改失败，没有访问数据权限");
        }
        operatorUserService.insertUserAuth(userId, roleIds,tenantId);
        return R.success();
    }

    /**
     * 根据用户编号获取授权角色
     */
    @GetMapping("system/role/authUser/unallocatedList")
    public R unallocatedList(SysUserVo user) {
        List<SysUser> list = operatorUserService.unallocatedList(user);
        PageUtil.PageResult<SysUser> paginate = PageUtil.paginate(list, user.getPageNum(), user.getPageSize());
        return R.success(paginate);
    }


    @PutMapping("system/role/authUser/cancel")
    public R cancelAuthUser(@RequestBody SysUserRole userRole)
    {
        return R.success(operatorUserService.deleteAuthUser(userRole));
    }

    @PutMapping("system/role/authUser/cancelAll")
    public R cancelAuthUserAll(Long roleId, Long[] userIds)
    {
        return R.success(operatorUserService.deleteAuthUsers(roleId, userIds));
    }




}
